import TableFilter from '@/components/TableSearch/filter';
import ToeUpload from '@/components/UploadDialog/index';
import {
  addAfterSalesNeedInfo,
  asnDownload,
  asnUploadFile,
  copyDetailById,
  delAfterSalesNeedInfo,
  getAfterSalesNeedInfoByPage,
  updateAfterSalesNeedInfo,
  updateModifySuggestion,
  updateSalesStatus,
} from '@/services/sales/salesNeedInfo';
import { PlusOutlined } from '@ant-design/icons';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { Button, Form, Input, message, Modal } from 'antd';
import React, { useRef, useState } from 'react';
import { history, useAccess } from 'umi';
const SalesNeedInfoCustomer: React.FC<{}> = () => {
  const [modalVisit, setModalVisit] = useState(false); // 新建和编辑提示框
  const [modalVisit2, setModalVisit2] = useState(false); // 新建和编辑提示框
  const [deleteVisit, setDeleteVisit] = useState(false); // 删除提示框
  const [showRole, SetShowRole] = useState(false); //显示角色
  const [filterVisit, SetFilterVisit] = useState(false); //显示高级弹框
  const [showUploadFile, SetShowUploadFile] = useState(false); //显示上传预览
  const [formTitle, setFormTitle] = useState('新建售后需求'); //
  const [createOrUpdate, setCreateOrUpdate] = useState(false); //编辑框的disable
  const [rowData, setRowData] = useState({ id: '' }); // 保存行值
  const actionRef = useRef<ActionType>();
  const [form] = Form.useForm();
  const [form2] = Form.useForm();
  const access = useAccess(); // access 实例的成员: canReadFoo, canUpdateFoo, canDeleteFoo
  const uploadRef = useRef(null);
  const [uploadVisit, setUploadVisit] = useState(false); //上传按钮显示
  const { TextArea } = Input;
  const [filterValue, SetFilterValue] = useState({});
  /**
   * 穿梭框的数据设置
   */
  const columnsAdmin: ProColumns[] = [
    {
      title: '序号',
      dataIndex: 'index',
      valueType: 'index',
      width: 80,
    },
    {
      title: '设备信息编号', //表头显示的名称
      search: false,
      dataIndex: 'identification', // 列数据在数据项中对应的路径，支持通过数组查询嵌套路径
      render: (text, record, _, action) => (
        <a
          key="linkkey"
          onClick={() => {
            // console.log(record, '----测试----');
            // 编辑用户
            history.push({
              pathname: `/sales/salesNeedInfoDetail`,
              query: {
                id: record.id,
              },
            });
          }}
        >
          {text}
        </a>
      ),
    },
    {
      title: '订货号', //表头显示的名称
      search: false,
      dataIndex: 'licenseOrderNum',
      valueType: 'dateRange',
    },

    {
      title: '创建时间', //表头显示的名称
      search: false,
      dataIndex: 'createDate',
    },
    {
      title: '设备名称', //表头显示的名称

      dataIndex: 'deviceName',
    },

    {
      title: '驱动数量', //表头显示的名称
      search: false,
      dataIndex: 'licenseCount',
    },

    {
      title: '进度', //表头显示的名称
      search: false,
      dataIndex: 'status',
      valueEnum: {
        1: { text: '保存', status: 'Warning' },
        2: { text: '提交', status: 'Default' },
        3: { text: '工程师正在处理', status: 'Processing' },
        4: { text: '需求修改', status: 'Processing' },
        5: { text: '工程师处理完成', status: 'Success' },
        6: { text: '软件包可以下载', status: 'Success' },
        7: { text: '调试中', status: 'Success' },
      },
    },

    {
      title: '修改意见', //表头显示的名称
      search: false,
      dataIndex: 'suggestionTitle',
      render: (text, record, _, action) => (
        <a
          key="linkkey"
          onClick={() => {
            Modal.confirm({
              title: record.suggestionTitle,
              content: record.modifySuggestion,
              okText: '确认',
              cancelText: '取消',
              onOk: async () => {
                // await DelUser({ id: record.id });
                // actionRef.current.reload();
              },
            });
          }}
        >
          {text}
        </a>
      ),
    },
    {
      title: '所属客户', //表头显示的名称
      search: false,
      dataIndex: 'customerName',
    },

    {
      title: '所属用户', //表头显示的名称
      search: false,
      dataIndex: 'userName',
    },

    {
      title: '创建人', //表头显示的名称
      search: false,
      dataIndex: 'createName',
    },

    {
      title: '操作',
      valueType: 'option',
      key: 'option',
      fixed: 'right',
      render: (text, record, _, action) => {
        const arrayButton = [];
        if (access.aperatorFilter('salesDelete')) {
          arrayButton.push(
            <a
              key="deleteKey"
              onClick={() => {
                setRowData(record);
                actionRef.current.reload();
                setDeleteVisit(true);
                // actionRef.current.reload();
              }}
            >
              删除
            </a>,
          );
        }
        arrayButton.push(
          <a
            key="route"
            onClick={() => {
              setRowData(record);
              history.push({
                pathname: `/sales/technicalSupportDetail`,
                query: {
                  orderId: record.id,
                },
              });
              // actionRef.current.reload();
            }}
          >
            技术支持
          </a>,
        );

        if (record.status === 2) {
          arrayButton.push(
            <a
              key="confirmKey"
              onClick={() => {
                Modal.confirm({
                  title: '处理确认',
                  content: '确定把状态变成处理中吗',
                  okText: '确认',
                  cancelText: '取消',
                  onOk: async () => {
                    await updateSalesStatus({ id: record.id, status: 3 });
                    actionRef.current.reload();
                  },
                });
              }}
            >
              处理确认
            </a>,
          );
        }

        if (record.status === 3) {
          arrayButton.push(
            <a
              key="ConfirmedDone"
              onClick={() => {
                Modal.confirm({
                  title: '处理完成',
                  content: '确定把状态变成处理完成吗',
                  okText: '确认',
                  cancelText: '取消',
                  onOk: async () => {
                    await updateSalesStatus({ id: record.id, status: 5 });
                    actionRef.current.reload();
                  },
                });
              }}
            >
              处理完成
            </a>,
          );
          arrayButton.push(
            <a
              key="suggekey"
              onClick={() => {
                setRowData(record);
                setModalVisit2(true);
                form2.setFieldsValue({
                  suggestionTitle: record.suggestionTitle,
                  id: record.id,
                  modifySuggestion: record.modifySuggestion,
                });

                // form2.resetFields();
                //
                // setModalVisit2(true);
              }}
            >
              提出修改意见
            </a>,
          );
        }

        if (record.status === 5 || record.status === 6) {
          arrayButton.push(
            <a
              key="uploadKey"
              onClick={() => {
                // console.log(record, '----测试----');
                // 编辑用户
                // setModalVisit(true);
                // setCreateOrUpdate(true);
                // setFormTitle('编辑设备');
                // form.setFieldsValue({
                //   name: record.name,
                //   id: record.id,
                // });
                // 导入文件
                // downloadFromMinio({ id: record.id }).then((res) => {
                //   const aLink = document.createElement('a');
                //   document.body.appendChild(aLink);
                //   aLink.style.display = 'none';
                //   aLink.href = window.URL.createObjectURL(res);
                //   aLink.setAttribute('download', `${record.fileName}`);
                //   aLink.click();
                //   document.body.removeChild(aLink);
                // });
                setRowData(record);
                setUploadVisit(true);
              }}
            >
              上传文件
            </a>,
          );
        }

        return arrayButton;
      },
    },
  ];

  const columnsCustomer: ProColumns[] = [
    {
      title: '序号',
      dataIndex: 'index',
      valueType: 'index',
      width: 80,
    },
    {
      title: '设备信息编号', //表头显示的名称
      dataIndex: 'identification', // 列数据在数据项中对应的路径，支持通过数组查询嵌套路径
      render: (text, record, _, action) => (
        <a
          key="editKey"
          onClick={() => {
            // console.log(record, '----测试----');
            // 编辑用户
            history.push({
              pathname: `/sales/salesNeedInfoDetail`,
              query: {
                id: record.id,
                status: record.status,
              },
            });
          }}
        >
          {text}
        </a>
      ),
    },
    {
      title: '订货号', //表头显示的名称
      search: false,
      hideInTable: true,
      dataIndex: 'licenseOrderNum',
    },

    {
      title: '创建时间', //表头显示的名称
      search: false,
      dataIndex: 'createDate',
    },

    {
      title: '进度', //表头显示的名称
      search: false,
      dataIndex: 'status',
      valueEnum: {
        1: { text: '保存', status: 'Warning' },
        2: { text: '提交', status: 'Default' },
        3: { text: '工程师正在处理', status: 'Processing' },
        4: { text: '需求修改', status: 'Processing' },
        5: { text: '工程师处理完成', status: 'Success' },
        6: { text: '软件包可以下载', status: 'Success' },
        7: { text: '调试中', status: 'Success' },
      },
    },

    {
      title: '设备名称', //表头显示的名称
      search: false,
      dataIndex: 'deviceName',
    },

    {
      title: '修改意见', //表头显示的名称
      search: false,
      dataIndex: 'suggestionTitle',
      render: (text, record, _, action) => (
        <a
          key="linkkey"
          onClick={() => {
            Modal.confirm({
              title: record.suggestionTitle,
              content: record.modifySuggestion,
              okText: '确认',
              cancelText: '取消',
              onOk: async () => {
                // await DelUser({ id: record.id });
                // actionRef.current.reload();
              },
            });
          }}
        >
          {text}
        </a>
      ),
    },

    {
      title: '驱动数量', //表头显示的名称
      search: false,
      dataIndex: 'licenseCount',
    },
    {
      title: '是否可以下载', //表头显示的名称
      search: false,
      hideInTable: true,
      dataIndex: 'download',
    },

    {
      title: '上传文件', //表头显示的名称
      search: false,
      hideInTable: true,
      dataIndex: 'fileName',
    },

    {
      title: '创建人', //表头显示的名称
      search: false,
      dataIndex: 'createName',
    },
    {
      title: '所属客户', //表头显示的名称
      search: false,
      hideInTable: true,
      dataIndex: 'customerName',
    },

    {
      title: '操作',
      valueType: 'option',
      key: 'option',
      fixed: 'right',
      render: (text, record, _, action) => {
        const operButtons = [];
        if (record.status === 6) {
          operButtons.push(
            <a
              key="editKey"
              onClick={() => {
                // console.log(record, '----测试----');
                // 编辑用户
                // setModalVisit(true);
                // setCreateOrUpdate(true);
                // setFormTitle('编辑设备');
                // form.setFieldsValue({
                //   name: record.name,
                //   id: record.id,
                // });
                // 导入文件
                asnDownload({ id: record.id }).then((res) => {
                  const aLink = document.createElement('a');
                  document.body.appendChild(aLink);
                  aLink.style.display = 'none';
                  aLink.href = window.URL.createObjectURL(res);
                  aLink.setAttribute('download', `${record.fileName}`);
                  aLink.click();
                  document.body.removeChild(aLink);
                });
              }}
            >
              下载
            </a>,
          );
        }
        if (access.aperatorFilter('salesDelete')) {
          operButtons.push(
            <a
              key="deleteKey"
              onClick={() => {
                setRowData(record);
                actionRef.current.reload();
                setDeleteVisit(true);
                // actionRef.current.reload();
              }}
            >
              删除
            </a>,
          );
        }

        operButtons.push(
          <a
            key="route"
            onClick={() => {
              setRowData(record);
              history.push({
                pathname: `/sales/technicalSupportDetail`,
                query: {
                  orderId: record.id,
                },
              });
              // actionRef.current.reload();
            }}
          >
            技术支持
          </a>,
        );
        operButtons.push(
          <a
            key="route"
            onClick={async () => {
              await copyDetailById({ id: record.id });
              actionRef.current.reload();
              // setRowData(record);
              // history.push({
              //   pathname: `/sales/technicalSupportDetail`,
              //   query: {
              //     orderId: record.id,
              //   },
              // });
              // actionRef.current.reload();
            }}
          >
            复制
          </a>,
        );
        return operButtons;
      },
    },
  ];

  const handleSubmit = async () => {
    if (formTitle == '新建售后需求') {
      const result = await addAfterSalesNeedInfo(form.getFieldsValue());
      console.log(result, '---测试---');
      if (result !== null) {
        console.log(result, '---');
        // message.success('添加成功');
      }
    } else {
      const result = await updateAfterSalesNeedInfo(form.getFieldsValue());
      if (result !== null) {
        message.success('更新成功');
      }
    }

    setModalVisit(false);
    // 这个爆红不用管(从新加载页面)
    actionRef.current.reload();
  };

  const handleSubmit2 = async () => {
    console.log(form2.getFieldsValue());
    console.log(rowData);
    // debugger;
    const result = await updateModifySuggestion({
      id: rowData.id,
      modified: 1,
      ...form2.getFieldsValue(),
    });
    if (result !== null) {
      message.success('更新成功');
    }

    setModalVisit2(false);
    // 这个爆红不用管(从新加载页面)
    actionRef.current.reload();
  };
  return (
    <PageHeaderWrapper title={false} breadcrumb={undefined}>
      <ProTable //表格Pro组件
        headerTitle="售后管理" //表头
        actionRef={actionRef} //用于触发刷新操作等，看api
        rowKey="id" //表格行 key 的取值，可以是字符串或一个函数
        scroll={{ x: 1600 }}
        toolBarRender={(action, { selectedRows }) => {
          const array = [];
          // array.push(<TableFilter />);
          if (access.aperatorFilter('salesPreview')) {
            array.push(
              <Button
                key="button"
                icon={<PlusOutlined />}
                onClick={() => {
                  // console.log(selectedRows, '---选取多行----');
                  // 1.清空form
                  history.push({
                    pathname: `/sales/salesNeedInfoDetail`,
                    // query: {
                    //   id: record.id,
                    // },
                  });
                }}
                type="primary"
              >
                售后预览
              </Button>,
            );
          }

          if (access.aperatorFilter('exportSaleExcel')) {
            array.push(
              <Button
                key="button"
                icon={<PlusOutlined />}
                onClick={() => {
                  // console.log(selectedRows, '---选取多行----');
                  // 1.清空form
                  history.push({
                    pathname: `/sales/salesNeedInfoDetail`,
                    // query: {
                    //   id: record.id,
                    // },
                  });
                }}
                type="primary"
              >
                导出Excel
              </Button>,
            );
          }

          if (access.aperatorFilter('salesNeedInfoCreate')) {
            array.push(
              <Button
                key="button"
                icon={<PlusOutlined />}
                onClick={() => {
                  // console.log(selectedRows, '---选取多行----');
                  // 1.清空form
                  history.push({
                    pathname: `/sales/salesNeedInfoDetail`,
                    // query: {
                    //   id: record.id,
                    // },
                  });
                }}
                type="primary"
              >
                新建售后
              </Button>,
            );
          }

          return array;
        }}
        request={async (params = {}, sort, filter) => {
          console.log(params, sort, filter);
          const sorters = [];
          for (const property in sort) {
            if (sort.hasOwnProperty(property)) {
              if (sort[property] == 'ascend') {
                sorters.push({
                  field: property,
                  desc: false,
                });
              } else {
                sorters.push({
                  field: property,
                  desc: true,
                });
              }
            }
            // 可以扩展
            console.log(property);
          }
          console.log(filterValue);
          const result = await getAfterSalesNeedInfoByPage({
            ...params,
            ...filterValue,
            sorters: sorters,
          });
          console.log(result);
          return {
            data: result.data.content,
            total: result.data.totalElements,
            success: result.success,
          };
          // return  await new Promise({data:[{loginName:}], total:10, success: 0})
          // return {data:[], total:10, success: 0}
        }} //请求数据的地方，例子是用mock模拟数据，我是在后台请求的数据
        columns={access.canAdmin() || access.canChiefEngineer() ? columnsAdmin : columnsCustomer} //上面定义的
        search={{
          defaultCollapsed: false,
          optionRender: (searchConfig, formProps, dom) => [
            ...dom.reverse(),
            <Button
              key="out"
              onClick={() => {
                SetFilterVisit(true);
              }}
            >
              高级搜索
            </Button>,
          ],
        }}
        rowSelection={{}}
      />

      <Modal
        title={formTitle}
        visible={modalVisit}
        onOk={handleSubmit}
        onCancel={() => setModalVisit(false)}
      >
        <Form
          name="wrap"
          labelCol={{ flex: '110px' }}
          labelAlign="left"
          labelWrap
          form={form}
          wrapperCol={{ flex: 1 }}
          colon={false}
        >
          <Form.Item label="id" name="id" hidden={true}>
            <Input />
          </Form.Item>
          <Form.Item
            label="设备信息编号"
            name="identification"
            rules={[{ required: true, message: 'Please input your code!' }]}
          >
            <Input disabled={createOrUpdate} />
          </Form.Item>

          <Form.Item
            label="订货标识"
            name="licenseOrderNum"
            rules={[{ required: true, message: 'Please input your code!' }]}
          >
            <Input disabled={createOrUpdate} />
          </Form.Item>

          {/* <Form.Item
            label="名称"
            name="name"
            hidden={createOrUpdate}
            rules={[{ required: true, message: 'Please input your password!' }]}
          >
            <Input />
          </Form.Item> */}
        </Form>
      </Modal>

      <Modal
        title="修改意见"
        visible={modalVisit2}
        onOk={handleSubmit2}
        onCancel={() => setModalVisit2(false)}
      >
        <Form
          name="wrap"
          labelCol={{ flex: '110px' }}
          labelAlign="left"
          labelWrap
          form={form2}
          wrapperCol={{ flex: 1 }}
          colon={false}
        >
          <Form.Item name="suggestionTitle" label="意见标题">
            <Input />
          </Form.Item>
          <Form.Item name="modifySuggestion" label="意见内容">
            <TextArea rows={4} />
          </Form.Item>
        </Form>
      </Modal>

      <Modal
        title="删除框提示?"
        visible={deleteVisit}
        onOk={async () => {
          console.log('----删除前的提示---', rowData);
          await delAfterSalesNeedInfo({ id: rowData.id });
          actionRef.current.reload();
          setDeleteVisit(false);
        }}
        onCancel={() => {
          setDeleteVisit(false);
        }}
      >
        <p>确认删除设备信息</p>
      </Modal>

      <TableFilter
        visible={filterVisit}
        onCancel={() => {
          SetFilterVisit(false);
        }}
        onFinish={(value) => {
          console.log(value, '--onFinish---');
          SetFilterValue(value);
          SetFilterVisit(false);
        }}
        columns={columnsAdmin}
      />
      <ToeUpload
        onCancel={() => {
          setUploadVisit(false);
        }}
        ref={uploadRef}
        onOk={async () => {
          const formData = new FormData();
          console.log(uploadRef.current.fileList, '文件测试---');
          uploadRef.current.fileList.map((file) => {
            formData.append('file', file);
          });
          formData.append('afterSalesNeedInfoId', rowData.id);
          // formData.append('file', 'jja');
          console.log(formData, '---formData--');
          await asnUploadFile(formData);
          setUploadVisit(false);
          actionRef.current.reload();
        }}
        visible={uploadVisit}
        title="文件上传"
      />
    </PageHeaderWrapper>
  );
};

export default SalesNeedInfoCustomer;
